// 引入基本核心包
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

// 引入导航栏、左侧栏、用户实体
import { NavigationEntity } from './share/../../models/navigation-entity';
import { LeftNavEntity } from '../models/left-nav-entity';
import { UserModel } from '../models/login/user-model';

// 引入权限、拦截器服务和Observable对象
import { AuthGuardService } from '../share/auth-guard.service';
import { InterceptorService } from '../share/interceptor.service';
import { Observable } from 'rxjs/Observable';
// 引入组件库-primeng
import { MenuItem } from 'primeng/primeng';
//import { fadeIn } from '@angular/animations/fade-in';
import { Console } from '@angular/core/src/console';


@Component({
  selector: 'app-workspace',
  templateUrl: './workspace.component.html',
  styleUrls: ['./workspace.component.css'],
  providers: [AuthGuardService]
  // animations: [fadeIn]
})
export class WorkspaceComponent implements OnInit {

  /**
   * ---------------实例化登录用户实体-----------------------------------------
   */
  public user: UserModel = new UserModel();
  /**
   * ---------------------实例化左侧栏菜单实体------------------------------------
   */
  leftmenu: LeftNavEntity[] = new Array<LeftNavEntity>();
  isLeftMenu = true; // 左侧栏按钮
  /**
   *-------------------------------- 实例化导航栏菜单实体----------------------------
   * navigations: Array<NavigationModel> 声明
   * navigations: Array<NavigationModel> = [];  初始化
   */
  navigations: Array<NavigationEntity> = [];
  navigationsMulti: Array<NavigationEntity> = []; // 用于存储过多的菜单
  style: any; // 导航栏样式
  items: MenuItem[]; // 导航栏‘更多’下拉菜单
  isTopMenu = false;  // 导航栏按钮
  tocken = "";
  projectId = 'TTYDYyuyuiiasdfas78rtR';
  /**
   * ----------------------------------登录成功加载导航栏服务-----------------------
   */
  // array = [ 1 ];
  ngOnInit() {
    // setTimeout(_ => {
    //   this.array = [ 1, 2, 3, 4 ];
    // }, 500);
    /**
     * TODO
     * ------------------------用require动态加载的外部JS----------------------------
     */
    /*使用如果没tockenid则不能进行登录操作,跳转到登录界面*/

    this.tocken = localStorage.getItem('Authorization')
    if (this.tocken == "" || this.tocken == null) {
      this.router.navigateByUrl('login');
    }
    // require("assets/js/customService");
    console.log("进入首页初始化界面");
    this.getNavigation();
    this.style = {
      'height': window.outerHeight - 150 + 'px'
    }
    //识别身份，自动跳转
    // this.autoIdentificate();
  }

  /**
   * --------------构造函数实例化权限、路由、拦截器服务----------------------------
   * @param authGuardService  权限
   * @param router  路由
   * @param http 拦截器
   */
  constructor(
    public authGuardService: AuthGuardService,
    public router: Router,
    private http: InterceptorService
  ) { }

  /**
 * -----------------------------导航栏服务页面加载时显示与隐藏-------------------------
 * @param el 
 */
  title(el: HTMLElement) {
    if (el.style.visibility === 'hidden') {
      el.style.visibility = 'visible';
    }
    this.isTopMenu = !this.isTopMenu;
    this.isLeftMenu = true;

  }
  /**
   * -------------------------------导航栏服务资源加载----------------------------------
   * 前端本地存储，提高性能，但由于导航栏服务存在多项判断所以需要重新审视-暂且没有添加
   */
  getNavigation() {
    console.log('------------------------开始进入查询顶级菜单方法-----------------------');
    const navigationURL = 'authorizationManagement-web/AuthorityManager/queryUserServiceApplication';
    const url = navigationURL + '/' + this.authGuardService.getUserId() + '/' + this.projectId;

    /*使用url传送token和userId */
    this.http.get(url)
      .subscribe(
        res => {
          const temp_naviagtion: NavigationEntity[] = res.json().data;

          if (temp_naviagtion.length <= 6) {
            this.navigations = res.json().data;
          } else {
            for (let i = 0; i < 6; i++) {
              this.navigations[i] = temp_naviagtion[i];
            }
            for (let j = 6; j < temp_naviagtion.length; j++) {
              this.navigationsMulti[j - 6] = temp_naviagtion[j];
            }
            this.items = [{ label: '更多', items: [] }];
            localStorage.setItem('navigationsMulti', JSON.stringify(this.navigationsMulti));

          }
        },
        error => console.error(error)

      );
  }


  /**
 * ----------------------------角色拥有服务超过六种出现更多按钮------------------------
 */
  openOtherMenu() {
    const otherNavigation: Array<NavigationEntity> = JSON.parse(localStorage.getItem('navigationsMulti'));
    this.items[0].items = [];
    for (let i = 0; i < otherNavigation.length; i++) {
      const item: MenuItem = { label: '更多', command: () => { } };
      item.label = otherNavigation[i].applicationName;
      const id: string = otherNavigation[i].id;
      item.command = (click) => this.openLeft(id);
      this.items[0].items[i] = item;
    }
  }

  /**
   * -------------------------导航栏右侧用户名显示----------------------------------
   */
  userName: string = localStorage.getItem('userName');

  leftBarFlag = true;
  changeLeftBarClass(): void {
    this.leftBarFlag = !this.leftBarFlag;
  }
  /**
   * ------------------------显示左侧栏-----------------------------------------------
   * 左侧栏资源已在前端本地缓存，存储时，先判断前端本地缓存是否存在，如果有，直接从本地获取
   * 如果没有，再与后台交互
   * @param applicationParentId 
   */
  public openLeft(applicationParentId: string) {
    this.isLeftMenu = false;
    this.leftBarFlag = true;//折叠中间部分
    const leftNavigationURL = 'authorizationManagement-web/AuthorityManager/queryServiceModuleApplication';
    const url = leftNavigationURL + '/' + this.authGuardService.getUserId() + '/' + applicationParentId;

    this.getLeftData(url);
    // -------------------------------------- 导航栏菜单点击时定位-------
    let e1: Element = document.getElementById(localStorage.getItem("activebtn"));
    if (e1 != null) { e1.removeAttribute("class"); }
    let e: Element = document.getElementById(applicationParentId);
    // ------------------dom操作要判断是否null,否则会报错--------------------
    if (e != null) { e.setAttribute("class", "nav-menu_active"); }
    localStorage.setItem("activebtn", applicationParentId);
  }

  /**
   * ---------------------左侧栏资源请求------------------------------------------------
   * @param url
   */
  getLeftData(url: string) {
    this.http.get(url).subscribe(
      res => {
        console.log(res);
        this.leftmenu = res.json();
        console.log(this.leftmenu);
        console.log('-------------------前端本地存储左侧栏资源-----------------------------');
        localStorage.setItem('leftInfo', JSON.stringify(this.leftmenu));
        console.log(localStorage.getItem('leftInfo'));
        // return this.leftmenu;
      }
    )
  }

  /**
   * todo 
   *出现页面叠加问题解决方案之一：进行错误处理，跳转到主页
   */
  public handleError(error: Response) {
    this.router.navigateByUrl('login');
    return Observable.throw(error.json() || 'server error');
  }

  /**
 * --------------------------------------点击左侧栏加载相应页面资源-------------------
 * @param menuId 
 */
  skipMenu(menuId: string) {
    this.leftmenu.forEach(item => {
      this.findPageUrl(item, menuId);
      localStorage.setItem('pageApplicationId', menuId);
      // console.log(item, menuId + '菜单');   
    });
    // -------------------------------------- 左侧栏菜单点击时定位
    let e1: Element = document.getElementById(localStorage.getItem("activebutton"));
    if (e1 != null) { e1.removeAttribute("class"); }
    let e: Element = document.getElementById(menuId);
    // ------------------dom操作要判断是否null,否则会报错--------------------
    if (e != null) { e.setAttribute("class", "left_submenu_active"); }
    localStorage.setItem("activebutton", menuId);
  }

  /**
   * --------------------------------递归实现左侧栏多级路由加载--------------------------------
   * @param eachItem 
   * @param menuId 
   */
  findPageUrl(eachItem: any, menuId: string) {
    if (eachItem.type === '页面') {
      console.log('加载每一级页面');
      if (eachItem.id === menuId) {
        console.log('加载每一级页面1');
        //alertalert(eachItem.applicationUrl);
        this.router.navigateByUrl(eachItem.applicationUrl);
        console.log(eachItem.applicationUrl + '递归实现左侧栏多级路由加载');
      }
    } else {
      eachItem.childs.forEach(item => {
        this.findPageUrl(item, menuId);
        console.log('加载每一级页面2');
      }

      )
    }
  }

  // ------------------------------------------------------------------------------------

  private test(obj: HTMLElement) {
    if ('hidden' === obj.style.visibility) {
      obj.style.visibility = '';
    } else {
      obj.style.display = 'none';
    }
  }
  /**
   * -------------------------------------------------退出系统--------------------------------
   * 清除后台redis缓存
   */
  quit() {
    /**
     * 退出跳转到登录页
     */
    const userCode = localStorage.getItem('userCode');
    const quitURL = 'authorizationManagement-web/access/logout/' + userCode;
    console.log('========================退出按钮===============================');

    this.http.get(quitURL).subscribe(
      res => {
        console.log(res);
        if (res.json().code == '0000') {

          this.router.navigateByUrl('login');
          /**
         * 退出清除前台缓存
         */
          localStorage.clear();
        }
      }
    );
  }
}